import React, { Component } from 'react';
import config from '../../pages/list/config';
import requestApi from '../../../../expenseaccount/wallet/card/requestApi';
import TicketBag from '../../../../expenseaccount/wallet/bag';
import CheckInVoice from "../../../../expenseaccount/wallet/check-invoice";
import { onSearchButtonClick } from '../../pages/list/events';
import { toast } from 'nc-lightapp-front';
import imgUrl from "../../components/table-area/img/bag-contro.svg";

import './index.less';
class Table extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // 是否显示左侧票袋列表
            bagIsHidden: false,
            // 是否显示右侧查验发票
            checkInvoceIsHidden: true,
            // 移动到按钮的列表加载数组
            ticketBagArr: [
                //     {
                //         "pk_erminvoice_bag":"all", // 唯一标志
                //         "bagname":"全部",// 票袋名称
                //         "pk_psndoc":"1001A51000000000301A",
                //         "pk_group":"0001A5100000000012MI",
                //         "pk_org":"0001A5100000000072UO",
                //         "dr":"0",
                //         "ts":"2022-05-1717:15:59",
                //         "valueIndex":{},
                //         "status":"0",
                //         "m_isDirty":false
                //     }
                ]
        },
        // 调用子集组件~~~~左侧票袋列表页
        this.onBagRef = this.onBagRef.bind(this),
        // 调用子集组件~~~~右侧发票展示页面
        this.onCheckInVoiceRef = this.onCheckInVoiceRef.bind(this),
        // 修改票袋当前活动触发的函数
        this.handleChangeActiveDataTableList = this.handleChangeActiveDataTableList.bind(this)
    }

    /**
     * @功能: 新增按钮触发的函数
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} e 
     */
    handleBagActiveId(params) {
        if(Object.keys(params).length > 0) {
            return this.bag.handleBagActiveId(params);
        }
    }



    //============================================================================移动到~~~开始
    /**
     * @功能:  请求后端刷新~~~移动到按钮的列表加载数组
     * @作者：Mr.sha
     * @日期：2022-06-08
     */
    queryBagMoveData(params) {
        // 当前活跃的ID
        let activeId = this.handleBagActiveId({});
        if(params && params.activeId){
            activeId = params.activeId;
        }
        if(this.props && this.props.getActiveId && params && params.type !== "init"){
            let paramsAct = {activeId}
            this.props.getActiveId(paramsAct);
        }
        const param = {pk_erminvoice_bag: activeId}
        requestApi.queryBagMoveData(
            {
                data: param,
                success: (data) => {
                    if(this.props && this.props.queryNCPopoverMove){
                        this.props.queryNCPopoverMove({data})
                    }
                    
                    this.setState({ticketBagArr: data});
                }
            }
        );
    }

    /**
     * @功能: 移动到
     * @作者：Mr.sha
     * @日期：2022-05-27
     * @param {*} params
     */
    moveBagSend(params){
        requestApi.bagMoveData({
            data: params,
            success: (data) => {
                toast({content: data[0]["message"],color:'success'});
                setTimeout(() => {
                    this.props.that.loadData(this.props.navTabStatus);
                    // 刷新左侧票袋列表
                    this.refreshLeftTicket()
                }, 1000);
            }
        })
    }
    //============================================================================移动到~~~结束

    /**
     * @功能: 刷新左侧票袋列表
     * @作者：wenlingli
     * @日期：2022-06-17
     */
    refreshLeftTicket(){
        this.bag.handleRefTableList({});
    }

    // moveBagPk showMoveTagModal

    /**
     * @功能: 修改票袋当前活动触发的函数
     * @作者：Mr.sha
     * @日期：2022-06-08
     * @returns 
     */
    handleChangeActiveDataTableList(params){
        this.queryBagMoveData(params);
        if(this.props && this.props.onHanleHiddenCheckInvoce) {
            this.props.onHanleHiddenCheckInvoce();
        }
    }
    
    /**
     * @功能: 获取bag组件对象
     * @作者：Mr.sha
     * @日期：2022-06-06
     * @param {*} e 
     */
     onBagRef = (ref) => {
        this.bag = ref
    }

    /**
     * @功能: 获取控制~票袋~显隐的class样式
     * @作者：Mr.sha
     * @日期：2022-06-07
     * @returns 
     */
    getBagShowDivClassNameArr() {
        let classNameArr = ['bag-show-hidden-init'];
        if(this.state && !this.state.bagIsHidden){
            classNameArr.push('bag-show-hidden-to-show')
        }
        return classNameArr.join(' ')
    }

    /**
     * @功能: 点击控制~票袋~显隐div的事件
     * @作者：Mr.sha
     * @日期：2022-06-07
     * @returns 
     */
    bagShowOrHidden() {
        this.setState({bagIsHidden: !this.state.bagIsHidden})
    }

    /**
     * @功能: 获取CheckInVoice组件对象
     * @作者：Mr.sha
     * @日期：2022-06-10
     * @param {*} checkInVoice 
     */
    onCheckInVoiceRef(checkInVoice) {
        this.checkInVoice = checkInVoice;
    }

    /**
     * @功能: 调用CheckInVoice组件对象的handleChangeInvoice方法
     * @作者：Mr.sha
     * @日期：2022-06-10
     * @param {*} params 
     */
    onhandleChangeInvoice(params) {
        if(this && this.checkInVoice){
            this.checkInVoice.onhandleChangeInvoice(params);
        }
        
    }

    // 组件挂载完成时触发的函数~~~只执行一次
    componentDidMount() {
        if(this.props && this.props.onTableAreaRef){
            this.props.onTableAreaRef(this)
        }  
        this.queryBagMoveData({type: "init"});
    }

    /**
     * @功能: 获取table列表的宽度
     * @作者：Mr.sha
     * @日期：2022-06-13
     */
    getAreaContentMainStyle() {
        let mainStyle = {width: "99%"};
        let styleWidth = 99;
        // 显示左侧的票袋
        if(!this.state.bagIsHidden && this.props && this.props.navTabStatus === "33" && this.props.that.listTabStatus === '0'){
            styleWidth -= 15;
        }
        // 显示右侧的发票
        if(!this.props.checkInvoceIsHidden ){
            styleWidth -= 39;
        }
        mainStyle = {width: styleWidth + "%"};
        return mainStyle;
    }

    /**
     * @功能: 获取票袋列表的宽度
     * @作者：Mr.sha
     * @日期：2022-06-13
     */
    getAreaContentLeftStyle() {
        let leftStyle = {width: "0%"};
        let styleWidth = 0;
        // 显示左侧的票袋
        if(!this.state.bagIsHidden){
            styleWidth = 15;
        }
        leftStyle = {width: styleWidth + "%"};
        return leftStyle;
    }

    /**
     * @功能: 获取查验发票的宽度
     * @作者：Mr.sha
     * @日期：2022-06-13
     */
    getAreaContentRightStyle() {
        let rightStyle = {width: "0%"};
        let styleWidth = 0;
        // 显示右侧的发票
        if(!this.props.checkInvoceIsHidden){
            styleWidth = 41;
        }
        rightStyle = {width: styleWidth + "%"};
        return rightStyle;
    }
    
    render() {
        let { createTransferTable, that} = this.props;
        // const multiLang = this.props.MutiInit.getIntl(2011); 
        return (
            <div className="nc-singleTable-table-area nc-singleTable-table-area-flex">
                {/* 左侧票袋列表 */}
                {
                    this.props && this.props.navTabStatus === "33" && that.listTabStatus === '0' &&
                    <div className='area-content-left' style = {this.getAreaContentLeftStyle()}>
                        <TicketBag 
                            onBagRef = {this.onBagRef}
                            bagIsHidden = {this.state.bagIsHidden}
                            handleChangeActiveDataTableList = {this.handleChangeActiveDataTableList}
                            handleDeleteDataTableList = {(params) => {
                                this.props.that.loadData(this.props.navTabStatus);
                            }}
                            transfertableMainHeight = {this.props.transfertableMain}
                        />
                        <div className = {this.getBagShowDivClassNameArr()}  onClick={() => {
                            this.bagShowOrHidden();
                        }}>
                            {/* 控制~票袋~显隐  */}
                            {/* <div className = {this.state.bagIsHidden ? 'bag-show-hidden-to-show-font' : 'bag-show-hidden-to-show-font-flip'}>
                                {this.props.multiLang['201103INUP-0016']}
                            </div> */}
                            <img className = "bag-show-hidden-to-show-img" src = {imgUrl} ></img>
                            
                        </div>
                    </div>
                }
            
                <div className = "area-content-main" style = {this.getAreaContentMainStyle()} >
                {createTransferTable(
                    {
                        headTableId: config.walletListArea,//表格组件id
                        bodyTableId: config.bodysArea,//子表模板id
                        fullTableId: config.bodysArea,//主子拉平模板id
                        showGenerateBtn: false, // 隐藏右下角按钮
                        comType: that.state.navTabStatus === '33' ? 'hasCheckBox_child' : '',
                        showSeletedBtn: that.state.navTabStatus === '33',
                        //点击加号展开，设置表格数据
                        containerSelector: '#transferInvoiceWallet', //容器的选择器 必须唯一,用于设置底部已选区域宽度
                        cacheItem:[],
                        showPagination:true,
                        onPageInfoChange: onSearchButtonClick.bind(that),
                        onCheckedChange: (flag, record, index, bodys) => {                   
                            //全选
                            if(Array.isArray(record)) {
                                const keys =  record.map(itm => itm.pk_erminvoice.value)
                                keys.forEach(key => {
                                    if (flag == true) {
                                        that.deleteList[key] = true
                                    } else if (flag == false) {
                                        that.deleteList[key] = false
                                        // that.checkedList = []
                                        that.setState({checkedList: []})
                                    }
                                })
                            } else {
                                //单选条件
                                const key = record.pk_erminvoice.value
                                let child_key = record.pk_erminvoice_b && record.pk_erminvoice_b.value
                                //勾选子表 -> 全选
                                let body_keys = []
                                that.invoiceList.forEach(item => {
                                    if(item.head.head.rows[0].values.pk_erminvoice.value === key) {
                                        if(item.body) {
                                            body_keys = item.body.body.rows.map(_itm => {  
                                                if(_itm.values.pk_erminvoice_b.value !== child_key) return _itm.values.pk_erminvoice_b.value }
                                            )
                                        }
                                    }
                                })
                                //只勾选兄弟元素，否则计算错误
                                body_keys = body_keys.filter(itm => itm && itm)
                                if(child_key && body_keys.length > 0 && flag) {
                                    that.props.transferTable.setTheCheckRows('head', body_keys)
                                }
                                if(child_key && body_keys.length > 0 && (!flag)) {
                                    that.props.transferTable.cancelRowsChecked('head', [key])
                                }

                                if (flag == true) {
                                    that.deleteList[key] = true
                                } else if (flag == false) {
                                    that.deleteList[key] = false
                                    // that.checkedList = []
                                    that.setState({checkedList: []})
                                }
                                console.log(that.deleteList)
                                if(flag === true && (that.deleteList && Object.keys(that.deleteList).length > 0)) {
                                    let checkedListNew = that.state.checkedList;
                                    checkedListNew.push({
                                        isOptimized: false,
                                        values: record
                                    })

                                    that.setState({checkedList: checkedListNew})
                                }
                                // console.log(that.checkedList,'checkedList======')
                            }
                        },
                    })}
                </div>

                {/* 右侧校验发票 */}
                <div className = 'area-content-right' style = {this.getAreaContentRightStyle()}>
                    <CheckInVoice onHanleHiddenCheckInvoce = {this.props.onHanleHiddenCheckInvoce} checkInvoceIsHidden = {this.props.checkInvoceIsHidden} 
                    onCheckInVoiceRef = {this.onCheckInVoiceRef}
                    invoiceList = {that.invoiceList}
                    />
                </div>
            </div>
        )
    }
}
export default Table;
